using System;
using System.Collections.Generic;
using System.Text;
using SongsDB;
using System.IO;
using System.Net;

namespace com.savage.mmtoxbmcexporter
{
    class XBMCPlaylistExporter
    {
        List<ISDBPlaylist> m_playlistList;
        List<string> m_m3uFileList;
        private string m_BaseDir;
        string m_replaceFromString;
        string m_replaceToString;
        ISDBApplication m_app;
        string m_XboxURL;
        string m_XboxUserName;
        string m_XboxPassword;

        public XBMCPlaylistExporter(ISDBApplication app, string replaceFromString, string replaceToString, string xboxURL, string xboxUserName, string xboxPassword)
        {
            m_playlistList = new List<ISDBPlaylist>();
            m_m3uFileList = new List<string>();
            m_replaceFromString = replaceFromString;
            m_replaceToString = replaceToString;
            m_BaseDir = Path.Combine(Path.GetTempPath(), "XBMC");
            m_app = app;
            Directory.CreateDirectory(m_BaseDir);

            m_XboxURL = xboxURL;
            m_XboxUserName = xboxUserName;
            m_XboxPassword = xboxPassword;
        }

        //public void Generate()
        //{
        //    AddPlaylists(m_app.get_PlaylistByTitle(""));
        //    GenerateM3UList();

        //    SendFilesToXbox(m_XboxURL, m_XboxUserName, m_XboxPassword);

        //}

        //private void SendFilesToXbox(string xboxURL, string xboxUserName, string xboxPassword)
        //{
        //    WebClient request = new WebClient();

        //    request.Credentials = new NetworkCredential(xboxUserName, xboxPassword);
        //    foreach (string file in m_m3uFileList)
        //    {
        //        try
        //        {
        //            string url = CombineURL(xboxURL, Xboxify(Path.GetFileName(file)));
        //            byte[] responseData = request.UploadFile(url, file);
        //            string responseString = System.Text.Encoding.UTF8.GetString(responseData);
        //            Console.WriteLine(responseString);
        //        }
        //        catch (WebException e)
        //        {
        //            Console.WriteLine(e.ToString());
        //        }
        //    }

        //}

        private string Xboxify(string name)
        {
            string newName = name.Replace("?", "");
            newName = name.Replace("!", "-");
            newName = name.Replace(",", "_");
            if (newName.Length > 38)
            {
                // truncate
                newName = newName.Substring(0, 38);
            }
            return newName;
        }

        private string CombineURL(string baseURL, string file)
        {
            if (!baseURL.EndsWith("/"))
            {
                baseURL += "/";
            }
            return baseURL + file;
        }

        //private void AddPlaylists(ISDBPlaylist parent)
        //{
        //    if (parent.Tracks.Count > 0)
        //    {
        //        m_playlistList.Add(parent);
        //    }
        //    SDBPlaylists childlists = parent.ChildPlaylists;
        //    for (int i = 0; i < childlists.Count; ++i)
        //    {
        //        AddPlaylists(childlists.get_Item(i));
        //    }
        //}

        //private void GenerateM3UList()
        //{
        //    foreach (ISDBPlaylist list in m_playlistList)
        //    {
        //        m_m3uFileList.Add(GenerateM3UFile(list));
        //    }
        //}

        public string GenerateM3UFile(ISDBPlaylist list, bool fixBackslashes, string replaceText, string replacerText)
        {
            string title = CorrectTitle(list.Title);
            string fileName = System.IO.Path.Combine(m_BaseDir, title + ".m3u");
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName);
            sw.WriteLine("#EXTM3U");
            ISDBSongList songList = list.Tracks;
            for (int i = 0; i < songList.Count; ++i)
            {
                SDBSongData song = songList.get_Item(i);
                string songName = System.IO.Path.GetFileNameWithoutExtension(song.Path);
                if (song.Title != null && song.Title != "")
                {
                    songName = song.Title;
                    string artist = song.Artist.Name;
                    if (artist != null && artist != "")
                    {
                        songName = string.Format("{0} - {1}", artist, songName);
                    }
                }

                sw.WriteLine(string.Format("#EXTINF:{0},{1}", (int)(song.SongLength / 1e3), songName));
                string path = song.Path;
                if (replaceText != null && replacerText != null)
                {
                    path = GetCorrectedPath(path, replaceText, replacerText);
                }
                if (fixBackslashes)
                {
                    path = this.fixBackslashes(path);
                }
                sw.WriteLine(path);
            }
            sw.Close();
            return fileName;
        }

        //public void SendFileToXbox(string localFileName, 

        private string CorrectTitle(string title)
        {
            return m_app.Tools.FileSystem.CorrectFilename(title);
        }

        private string fixBackslashes(string path)
        {
            return path.Replace("\\", "/");
        }

        private string GetCorrectedPath(string path, string replaceText, string replacerText)
        {
            return path.Replace(replaceText, replacerText);
        }


    }
}
